import {getLoginUser} from "../../../service/user";
import {validateMobile} from "../../../utils/validate";
import {showToast, showToastError, showToastSuccess} from "../../../utils/tool";
import {simplePost} from "../../../utils/request";

Page({
    data: {
        nav:{
            title:"绑定手机号",
        },
        user:null,
        options:{},
        isSmsValidateSuccess:false,
        smsCode:'',
        newMobile:'',
        subLoading:true,
    },
    onLoad: function (options) {

        (async () => {
            const user = await getLoginUser()

            this.setData({
                user:user,
                options:options||{}
            })

        })()

    },

    smsCodeChange(e){
        this.setData({
            smsCode:e.detail.code
        })
    },

    saveMobile(){
        const {smsCode, newMobile} = this.data

        if(!smsCode || smsCode.length<6){
            showToastError("短信验证码错误")
            return
        }
        if (!newMobile || !validateMobile(newMobile)){
            showToastError("手机号格式错误")
            return
        }
        this.setData({
            subLoading:true,
        })

        simplePost("/user/change_mobile", {
            new_mobile:newMobile,
            new_m_code: smsCode,
        }).then(res => {
            showToastSuccess("绑定成功", {
                timeout:() => {
                    wx.navigateBack()
                }
            })
        }).finally(() => {
            this.setData({
                subLoading:false,
            })
        })
    },
    oldMobileValidateSms(){
        const {user,smsCode} = this.data
        simplePost('/public/validateVerifySms',{
            mobile:user.mobile,
            type:'change_mobile',
            code: smsCode,
        }).then(res => {
            this.setData({
                isSmsValidateSuccess:true,
            })
            showToastSuccess("验证成功")
        })
    }
});
